<script setup lang="jsx">

import {AddIcon, SearchIcon} from "tdesign-icons-vue-next";
import {computed, reactive, ref, onMounted} from 'vue';
import {useAdministratorStore} from "@/stores/administrator.js";
import {MessagePlugin} from "tdesign-vue-next";
import {
  createActivity, deleteActivityApi,
  deleteAdministratorApi,
  listActivityAdministrator,
  listAdministrator, reviewActivity, updateActivity
} from "@/api/administrator.js";
import {ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon} from 'tdesign-icons-vue-next';

const administratorStore = useAdministratorStore()

// 审核活动 -----------------------------------------------------------------------
const onClickReview = async (activityId, reviewStatus) => {
  const res = await reviewActivity(administratorStore, activityId, reviewStatus);
  if (res.data.data === true) {
    await MessagePlugin.success("操作成功");
    const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', '', '');
    data.value = res.data.data
    total.value = data.value.length
    pagination.total = total.value
  } else {
    await MessagePlugin.error("操作失败");
  }
}

// 活动编辑 ------------------------------------------------------------------------
const editForm = ref(null);
const activityApply = reactive({
  id: undefined,
  activityName: '',
  description: '',
  maxNum: 2,
  expirationTime: ref(formatDate(new Date())),
  type: '',

});

const editVisible = ref(false);
const editClose = () => {
  editVisible.value = false
}

const editWindow = (row) => {
  editVisible.value = true
  activityApply.id = row.id;
  activityApply.activityName = row.activityName;
  activityApply.description = row.description;
  activityApply.maxNum = row.maxNum;
  activityApply.expirationTime = row.expirationTime;
  activityApply.type = row.type;


}

const rules = {
  activityName: [
    { required: true, message: '活动名必填', type: 'error' },
  ],
  description: [
    { required: true, message: '活动描述必填', type: 'error' },
  ],
  maxNum: [
    { required: true, message: '人数必填，且最少两人', type: 'error' },
    { number: true, message: '请输入数字', type: 'warning' },
  ],
  type: [
    { required: true, message: '类型必填', type: 'error' },
  ],
};

// 活动类型
const LIST = ['体育','学科竞赛','文化艺术','社会实践','休闲娱乐'];
const options = ref([...LIST]);
const onReset = () => {
  MessagePlugin.success('重置成功');
};

const onSubmitEdit = async () => {
  const res = await updateActivity(administratorStore,activityApply.id ,activityApply.activityName,activityApply.description,activityApply.maxNum,activityApply.expirationTime,activityApply.type);
  if (res.data.data !== true) await MessagePlugin.error("修改失败: "+ res.data.description);
  else {
    await MessagePlugin.success("修改成功")
    const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', radioButton.value, '');
    data.value = res.data.data
    total.value = data.value.length
    pagination.total = total.value
    editVisible.value = false
  }
};

const handleClear = () => {
  editForm.value.clearValidate();
};

const error = ref(undefined);
const tips = computed(() => {
  if (error.value === 'exceed-maximum') return 'number can not be exceed maximum';
  if (error.value === 'below-minimum') {
    activityApply.maxNum = 2
    return '最少为两人';
  }
  return undefined;
});

const onValidate = (p) => {
  error.value = p.error;
};

// 创建活动 --------------------------------------------------------------
const createForm = ref(null);
const activityApplyCreate = reactive({
  activityName: '',
  description: '',
  maxNum: 2,
  expirationTime: ref(formatDate(new Date())),
  type: '',

});

const createVisible = ref(false);
const createClose = () => {
  createVisible.value = false
}

const createWindow = (row) => {
  createVisible.value = true
}

const onSubmitCreate = async () => {
  const res = await createActivity(administratorStore, activityApplyCreate.activityName,activityApplyCreate.description,activityApplyCreate.maxNum,activityApplyCreate.expirationTime,activityApplyCreate.type);
  if (res.data.data !== true) await MessagePlugin.error("创建失败: "+ res.data.description);
  else {
    await MessagePlugin.success("创建成功")
    const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', radioButton.value, '');
    data.value = res.data.data
    total.value = data.value.length
    pagination.total = total.value
    createVisible.value = false
  }
  console.log(activityApplyCreate)
}

// 当前的时间 -------------------------------------------------------------
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}



// 搜索 --------------------------------------------------------------------------

const searchValue = ref('');
const onClear = () => {
  console.log('clear');
  search()
};
const onBlur = () => {
  console.log('blur');
  if (searchValue.value === '') {
    search()
  }
};

const search = async ()=> {
  const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', radioButton.value, '');
  data.value = res.data.data
  total.value = data.value.length
  pagination.total = total.value
}

// 表格数据 ------------------------------------------------------------------------
const data = ref([])
const total = ref(0)

const stripe = ref(true);
const bordered = ref(false);
const hover = ref(true);
const size = ref('medium');
const showHeader = ref(true);

const radioButton = ref(1);
const onClickRadioButton = async (value) => {
  const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', value, '');
  radioButton.value = value
  data.value = res.data.data
  total.value = data.value.length
  pagination.total = total.value
}

const refreshData = async () => {

}

// -- 表格删除JSX --------------------------------------------------------------------
const deleteVisible = ref(false);
const deleteId = ref();
const deleteName = ref('');
const deleteActivity = (row) => {
  deleteVisible.value = true
  deleteId.value = row.id
  deleteName.value = row.activityName
}

const deleteClose = () => {
  deleteVisible.value = false;
  deleteId.value = null;
};
const onClickConfirmDelete = async (context) => {
  const {e} = context;
  const res = await deleteActivityApi(administratorStore, deleteId.value);
  if (res.data.data === true) {
    await MessagePlugin.success("删除成功");
    deleteVisible.value = false;
    const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', radioButton.value, '');
    data.value = res.data.data
    total.value = data.value.length
    pagination.total = total.value

  } else {
    await MessagePlugin.error("删除失败: " + res.data.description)
  }

  e.stopPropagation();
};

const statusNameListMap = {
  1: {label: '审核通过', theme: 'success', icon: <CheckCircleFilledIcon/>},
  2: {label: '审核拒绝', theme: 'danger', icon: <CloseCircleFilledIcon/>},
  0: {label: '待审核', theme: 'warning', icon: <ErrorCircleFilledIcon/>},
};

const columns = ref([
  {colKey: 'id', title: '活动id', width: 40},
  {colKey: 'activityName', title: '活动名称', width: 70},
  {
    colKey: 'description', title: '描述', width: 100,
    ellipsis: true
  },
  {colKey: 'maxNum', title: '最大人数', width: 50},
  {colKey: 'expirationTime', title: '截止时间', width: 80},
  // {colKey: 'applicant', title: '申请人id', width: 50},
  {colKey: 'type', title: '活动类别', width: 80},
  {colKey: 'reviewer', title: '审核人', width: 50},
  {
    colKey: 'activityStatus',
    title: '活动状态',
    cell: (h, {row}) => {
      return (
          <t-tag shape="round" theme={statusNameListMap[row.activityStatus].theme} variant="light-outline">
            {statusNameListMap[row.activityStatus].icon}
            {statusNameListMap[row.activityStatus].label}
          </t-tag>
      );
    },
    width: 100
  },
  {
    colKey: 'option',
    title: '选项',
    width: 100,
    cell: (h, {row}) => {
      if (row.activityStatus === 0) {
        return (
            <t-space>
              <t-button theme="success" size="small" onClick={() => onClickReview(row.id, 1)}>通过</t-button>
              <t-button theme="danger" size="small" onClick={() => onClickReview(row.id, 2)}>拒绝</t-button>
              <t-button theme="primary" size="small" onClick = {()=>editWindow(row)}>编辑</t-button>

            </t-space>
        )
      } else if (row.activityStatus === 1) {
        return (
            <t-space>
              <t-button theme="primary" size="small" onClick={() => editWindow(row)}>编辑</t-button>
              <t-button theme="danger" size="small" onClick={() => deleteActivity(row)}>删除</t-button>
            </t-space>
        )
      } else {
        return (
            <t-space>
              <t-button theme="danger" size="small" onClick={() => deleteActivity(row)}>删除</t-button>
            </t-space>
        )
      }
    },
  }

]);

const handleRowClick = (e) => {
  console.log(e);
};

const pagination = {
  defaultCurrent: 1,
  defaultPageSize: 5,
  total: 0,
};

// 初始化数据 ---------------------------------------------
onMounted(async () => {
  const res = await listActivityAdministrator(administratorStore, searchValue.value, '', '', '', '', 1, '');
  data.value = res.data.data
  total.value = data.value.length
  pagination.total = total.value

})



</script>

<template>
  <t-layout style="
      height: 100%;                /* 继承父容器高度 */
    ">
    <t-header style="display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 2%;
      padding-right: 1%;
      background-color: #e5e5e5;
      width: auto;">
      <div style="display: flex; justify-content: flex-start; width: 100%">
        <t-radio-group style="background-color: #cccccc" variant="primary-filled" default-value="1">
          <t-radio-button value="1" @click="onClickRadioButton(1)">已通过</t-radio-button>
          <t-radio-button value="0" @click="onClickRadioButton(0)">未审核</t-radio-button>
          <t-radio-button value="2" @click="onClickRadioButton(2)">已拒绝</t-radio-button>
        </t-radio-group>
      </div>
      <div style="display: flex; justify-content: flex-end; width: 100% ">
        <div style="padding-right: 2%">
          <t-input v-model="searchValue" placeholder="输入活动" borderless clearable @clear="onClear"
                   @blur="onBlur"></t-input>
        </div>
        <div style="padding-right: 2%">
          <t-button shape="circle" theme="primary" @click="search">
            <template #icon>
              <SearchIcon/>
            </template>
          </t-button>
        </div>
        <div>
          <t-button shape="circle" theme="primary" @click="createWindow">
            <template #icon>
              <AddIcon/>
            </template>
          </t-button>
        </div>
      </div>


    </t-header>
    <t-content
        style="background-color: white; width: 100%; display: flex; align-items: center; justify-content: center">
      <t-space direction="vertical" style="padding: 2%;">

        <!-- 当数据为空需要占位时，会显示 cellEmptyContent -->
        <t-table
            row-key="index"
            :data="data"
            :columns="columns"
            :stripe="stripe"
            :bordered="bordered"
            :hover="hover"
            :table-layout="'fixed'"
            :size="size"
            :pagination="pagination"
            :show-header="showHeader"
            cell-empty-content="-"
            resizable
            lazy-load
            @row-click="handleRowClick"
            @page-change="refreshData"
        >
        </t-table>
      </t-space>
    </t-content>
    <t-dialog
        v-model:visible="deleteVisible"
        theme="danger"
        header="警示"
        :body="'确认要删除该活动吗？'+'活动名为：'+deleteName"
        :on-close="deleteClose"
        :cancel-btn="null"
        :confirm-btn="{ theme: 'danger', content: '确认删除' }"
        @confirm="onClickConfirmDelete"
    />

    <t-dialog placement="center" header="编辑活动" :footer="false" :visible="editVisible" :on-confirm="editClose"
              :on-close="editClose"
              width="50%">
      <t-divider/>
      <t-form ref="editForm" :data="activityApply" :rules="rules" @reset="onReset" @submit="onSubmitEdit" style="width: 50%">
        <t-form-item label="活动名" help="输入活动名，申请前请先查询有无类似活动" name="activityName">
          <t-input v-model="activityApply.activityName"></t-input>
        </t-form-item>
        <t-form-item label="活动描述" help="" name="description">
          <t-textarea
              v-model="activityApply.description"
              name="description"
              :autosize="true"
              :maxcharacter="100"
          />
        </t-form-item>

        <t-form-item label="最大人数" name="maxNum">
          <t-input-number
              :min="2"
              @validate="onValidate"
              :tips="tips"
              v-model="activityApply.maxNum" />
        </t-form-item>
        <t-form-item
            label="截止时间"
            name="expirationTime"
            :rules="[
        { required: true, message: '此项必填' },
      ]"
        >
          <t-date-picker v-model="activityApply.expirationTime" enable-time-picker clearable />
        </t-form-item>

        <t-form-item label="活动类型" name="type" help="选择该活动的类型">
          <t-auto-complete
              v-model="activityApply.type"
              :options="options"
              highlight-keyword
              filterable
              placeholder="类型"
              style="width: 280px"
          />
        </t-form-item>

        <t-form-item>
          <t-space size="small">
            <t-button theme="primary" type="submit">提交</t-button>
            <t-button theme="default" variant="base" type="reset">重置</t-button>
            <t-button theme="default" variant="base" @click="handleClear">清空校验结果</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

    <t-dialog placement="center" header="创建活动" :footer="false" :visible="createVisible" :on-confirm="createClose"
              :on-close="createClose"
              width="50%">
      <t-divider/>
      <t-form ref="createForm" :data="activityApplyCreate" :rules="rules" @reset="onReset" @submit="onSubmitCreate" >
        <t-form-item label="活动名" help="输入活动名，申请前请先查询有无类似活动" name="activityName">
          <t-input v-model="activityApplyCreate.activityName"></t-input>
        </t-form-item>
        <t-form-item label="活动描述" help="" name="description">
          <t-textarea
              v-model="activityApplyCreate.description"
              name="description"
              :autosize="true"
              :maxcharacter="100"
          />
        </t-form-item>

        <t-form-item label="最大人数" name="maxNum">
          <t-input-number
              :min="2"
              @validate="onValidate"
              :tips="tips"
              v-model="activityApplyCreate.maxNum" />
        </t-form-item>
        <t-form-item
            label="截止时间"
            name="expirationTime"
            :rules="[
        { required: true, message: '此项必填' },
      ]"
        >
          <t-date-picker v-model="activityApplyCreate.expirationTime" enable-time-picker clearable />
        </t-form-item>

        <t-form-item label="活动类型" name="type" help="选择该活动的类型">
          <t-auto-complete
              v-model="activityApplyCreate.type"
              :options="options"
              highlight-keyword
              filterable
              placeholder="类型"
              style="width: 280px"
          />
        </t-form-item>

        <t-form-item>
          <t-space size="small">
            <t-button theme="primary" type="submit">提交</t-button>
            <t-button theme="default" variant="base" type="reset">重置</t-button>
            <t-button theme="default" variant="base" @click="handleClear">清空校验结果</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>


  </t-layout>

</template>

<style scoped>

</style>